package org.visual.plugin.gme.wizard;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.ide.undo.CreateProjectOperation;

public class CreateMashupProjectOperation extends CreateProjectOperation {
	private IProject project;
	private IProjectDescription description;
	/**
	 * Create a CreateMashupProjectOperation
	 * 
	 * @param projectDescription
	 *            the project to be created
	 * @param label
	 *            the label of the operation
	 */
	public CreateMashupProjectOperation(IProject project, IProjectDescription projectDescription,
			String label) {
		super(projectDescription, label);
		this.project = project;
		this.description = projectDescription;
	}

	@Override
	protected void doExecute(IProgressMonitor monitor, IAdaptable uiInfo) throws CoreException {
		super.doExecute(monitor, uiInfo);
		createIndexFile(monitor);
	}

	@Override
	protected void doUndo(IProgressMonitor monitor, IAdaptable uiInfo) throws CoreException {
		// TODO Auto-generated method stub
		super.doUndo(monitor, uiInfo);
	}

	protected void createIndexFile(IProgressMonitor monitor) {
		try {
			IProjectDescription description = project.getDescription();
			String[] natures = description.getNatureIds();
			String[] newNatures = new String[natures.length + 1];
			System.arraycopy(natures, 0, newNatures, 0, natures.length);
			newNatures[natures.length] = "com.mushup.editor";
			description.setNatureIds(newNatures);
			project.setDescription(description, null);
		} catch (CoreException e) {
			// Something went wrong
		}

		String fileContent = WizardConfiguration.PROJECT_DEFAULT_FILE.replace(
				WizardConfiguration.PROJECT_NAME_PATTERN, description.getName());
		IFile indexFile = project.getFile(WizardConfiguration.PROJECT_FILE_NAME);
		InputStream inputStraem = null;
		try {
			inputStraem = new ByteArrayInputStream(fileContent.getBytes());
			indexFile.create(inputStraem, false, monitor);

		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStraem != null) {
				try {
					inputStraem.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
